/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.me.relex.photodraweeview.sample.slice;

import com.me.relex.photodraweeview.PhotoViewFrame;
import com.me.relex.photodraweeview.sample.CustomTitle;
import com.me.relex.photodraweeview.sample.ResourceTable;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.agp.animation.AnimatorProperty;
import ohos.agp.components.*;
import ohos.agp.utils.LayoutAlignment;
import ohos.agp.window.dialog.ToastDialog;
import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;
import ohos.multimodalinput.event.TouchEvent;

import java.text.DecimalFormat;

/**
 * demo首页 slice
 *
 * @since 2021-03-27
 */
public class SingleAbilitySlice extends AbilitySlice implements Component.ClickedListener,
        Component.LongClickedListener,
        Component.TouchEventListener,
        CustomTitle.MenuItemClickedListener {
    private static final float STEP_PHOTO_VIEW_FRAME = 0.25f;
    private static final int TOAST_SHOW_DURATION = 2 * 1000;
    private static final int TOAST_SHOW_Y = 200;
    private static final int ROTATE_ANIMATOR = 180;
    private static final int DURATION_ANIMATOR = 1000;
    private static final int LOOPED_COUNT_ANIMATOR = 2;

    private float mUpX;
    private float mUpY;
    private AnimatorProperty mAnimatorProperty;
    private PhotoViewFrame mPhotoViewFrame;
    private int mPosition = 0;

    private final DependentLayout mDependentLayout = new DependentLayout(this);
    private final DependentLayout mLoadingLayout = new DependentLayout(this);
    private final DependentLayout mContentLayout = new DependentLayout(this);
    private Image mLoadingImg;
    private Image mErrImg;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        CustomTitle customTitle = new CustomTitle(this);
        customTitle.setBackIconVisibility(false);
        customTitle.setTitle("PhotoDraweeView");
        customTitle.isShowMenu(true);
        customTitle.setMenuItemClickedListener(this);
        customTitle.setOnBackClickListener(() -> terminate());

        // 可缩放图片
        mPhotoViewFrame = new PhotoViewFrame(getContext());
        mPhotoViewFrame.setWidth(DirectionalLayout.LayoutConfig.MATCH_PARENT);
        mPhotoViewFrame.setHeight(DirectionalLayout.LayoutConfig.MATCH_PARENT);
        mPhotoViewFrame.setImageAndDecodeBounds(ResourceTable.Media_viewpager_2);

        // image
        mErrImg = new Image(getContext());
        mErrImg.setWidth(DirectionalLayout.LayoutConfig.MATCH_CONTENT);
        mErrImg.setHeight(DirectionalLayout.LayoutConfig.MATCH_CONTENT);
        mErrImg.setPixelMap(ResourceTable.Media_ic_error);
        mErrImg.setVisibility(Component.HIDE);

        // loading
        mLoadingImg = new Image(getContext());
        mLoadingImg.setWidth(DirectionalLayout.LayoutConfig.MATCH_CONTENT);
        mLoadingImg.setHeight(DirectionalLayout.LayoutConfig.MATCH_CONTENT);
        mLoadingImg.setPixelMap(ResourceTable.Media_ic_loading);

        mLoadingLayout.addComponent(mLoadingImg);
        mLoadingLayout.setWidth(DirectionalLayout.LayoutConfig.MATCH_PARENT);
        mLoadingLayout.setHeight(DirectionalLayout.LayoutConfig.MATCH_PARENT);
        mLoadingLayout.setAlignment(LayoutAlignment.CENTER);
        mLoadingLayout.setVisibility(Component.HIDE);

        mContentLayout.addComponent(mPhotoViewFrame);
        mContentLayout.addComponent(mErrImg);
        mContentLayout.setWidth(DirectionalLayout.LayoutConfig.MATCH_PARENT);
        mContentLayout.setHeight(DirectionalLayout.LayoutConfig.MATCH_PARENT);
        mContentLayout.setAlignment(LayoutAlignment.CENTER);
        mContentLayout.setClickedListener(this);
        mContentLayout.setLongClickedListener(this);
        mContentLayout.setTouchEventListener(this);

        mDependentLayout.addComponent(mContentLayout);
        mDependentLayout.addComponent(mLoadingLayout);
        mDependentLayout.addComponent(customTitle);
        mDependentLayout.setWidth(DirectionalLayout.LayoutConfig.MATCH_PARENT);
        mDependentLayout.setHeight(DirectionalLayout.LayoutConfig.MATCH_PARENT);
        super.setUIContent(mDependentLayout);
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }

    @Override
    public void onClick(Component component) {
        if (mPosition == 1) {
            DirectionalLayout toastLayout = (DirectionalLayout) LayoutScatter.getInstance(getContext())
                    .parse(com.me.relex.photodraweeview.ResourceTable.Layout_layout_toast, null, false);
            Text text = (Text) toastLayout.findComponentById(com.me.relex.photodraweeview.ResourceTable.Id_msg_toast);
            DecimalFormat df = new DecimalFormat("0.0000000");
            text.setText("onPhotoTap:x="
                    + df.format(mUpX / (mContentLayout.getWidth()))
                    + ";y=" + df.format(mUpY / (mContentLayout.getHeight() + mContentLayout.getTop())));
            new ToastDialog(getContext())
                    .setComponent(toastLayout)
                    .setSize(DirectionalLayout.LayoutConfig.MATCH_CONTENT, DirectionalLayout.LayoutConfig.MATCH_CONTENT)
                    .setAlignment(LayoutAlignment.BOTTOM)
                    .setDuration(TOAST_SHOW_DURATION)
                    .setOffset(0, TOAST_SHOW_Y)
                    .show();
        } else if (mPosition == 0 || mPosition == 4) {
            DirectionalLayout toastLayout = (DirectionalLayout) LayoutScatter.getInstance(this)
                    .parse(com.me.relex.photodraweeview.ResourceTable.Layout_layout_toast, null, false);
            Text text = (Text) toastLayout.findComponentById(com.me.relex.photodraweeview.ResourceTable.Id_msg_toast);
            text.setText("onViewTap");
            new ToastDialog(getContext())
                    .setComponent(toastLayout)
                    .setSize(DirectionalLayout.LayoutConfig.MATCH_CONTENT, DirectionalLayout.LayoutConfig.MATCH_CONTENT)
                    .setAlignment(LayoutAlignment.BOTTOM)
                    .setDuration(TOAST_SHOW_DURATION)
                    .setOffset(0, TOAST_SHOW_Y)
                    .show();
        } else {
        }
    }

    @Override
    public void onLongClicked(Component component) {
        DirectionalLayout toastLayout = (DirectionalLayout) LayoutScatter.getInstance(getContext())
                .parse(com.me.relex.photodraweeview.ResourceTable.Layout_layout_toast, null, false);
        Text text = (Text) toastLayout.findComponentById(com.me.relex.photodraweeview.ResourceTable.Id_msg_toast);
        text.setText("onLongClicked");
        new ToastDialog(getContext())
                .setComponent(toastLayout)
                .setSize(DirectionalLayout.LayoutConfig.MATCH_CONTENT, DirectionalLayout.LayoutConfig.MATCH_CONTENT)
                .setAlignment(LayoutAlignment.BOTTOM)
                .setDuration(TOAST_SHOW_DURATION)
                .setOffset(0, TOAST_SHOW_Y)
                .show();
    }

    @Override
    public boolean onTouchEvent(Component component, TouchEvent touchEvent) {
        if (touchEvent.getAction() == TouchEvent.PRIMARY_POINT_DOWN) {
            mUpX = touchEvent.getPointerPosition(0).getX();
            mUpY = touchEvent.getPointerPosition(0).getY();
        }
        return true;
    }

    @Override
    public void onItemClicked(int position) {
        mPosition = position;
        switch (position) {
            case 0:
                mLoadingLayout.setVisibility(Component.HIDE);
                mErrImg.setVisibility(Component.HIDE);
                mPhotoViewFrame.setVisibility(Component.VISIBLE);
                mPhotoViewFrame.setScaleStep(0);
                mPhotoViewFrame.initPhotoView();
                break;
            case 1:
                startFailureImage();
                break;
            case 2:
                startViewPager();
                break;
            case 3:
                startRecyclerView();
                break;
            case 4:
                mLoadingLayout.setVisibility(Component.HIDE);
                mErrImg.setVisibility(Component.HIDE);
                mPhotoViewFrame.setVisibility(Component.VISIBLE);
                mPhotoViewFrame.setScaleStep(STEP_PHOTO_VIEW_FRAME);
                mPhotoViewFrame.initPhotoView();
                break;
            case 5:
                startSharedElement();
                break;
            default:
                break;
        }
    }

    private void startViewPager() {
        Intent intentViewPager = new Intent();
        Operation operationViewPager = new Intent.OperationBuilder()
                .withDeviceId("")
                .withBundleName(getBundleName())
                .withAbilityName("com.me.relex.photodraweeview.sample.ViewPagerAbility")
                .build();
        intentViewPager.setOperation(operationViewPager);
        startAbility(intentViewPager);
    }

    private void startRecyclerView() {
        Intent intent = new Intent();
        Operation operation5 = new Intent.OperationBuilder()
                .withDeviceId("")
                .withBundleName(getBundleName())
                .withAbilityName("com.me.relex.photodraweeview.sample.RecyclerViewAbility")
                .build();
        intent.setOperation(operation5);
        startAbility(intent);
    }

    private void startSharedElement() {
        Intent intent = new Intent();
        Operation operation2 = new Intent.OperationBuilder()
                .withDeviceId("")
                .withBundleName(getBundleName())
                .withAbilityName("com.me.relex.photodraweeview.sample.SharedElementAbility")
                .build();
        intent.setOperation(operation2);
        startAbility(intent);
    }

    /**
     * Failure Image
     */
    private void startFailureImage() {
        mLoadingLayout.setVisibility(Component.VISIBLE);
        mErrImg.setVisibility(Component.HIDE);
        mPhotoViewFrame.setVisibility(Component.HIDE);
        mLoadingLayout.setTouchEventListener(this);

        mAnimatorProperty = mLoadingImg.createAnimatorProperty();
        mAnimatorProperty.rotate(ROTATE_ANIMATOR).setDuration(DURATION_ANIMATOR)
                .setLoopedCount(LOOPED_COUNT_ANIMATOR);

        mLoadingImg.setBindStateChangedListener(new Component.BindStateChangedListener() {
            @Override
            public void onComponentBoundToWindow(Component component) {
                mAnimatorProperty.start();
            }

            @Override
            public void onComponentUnboundFromWindow(Component component) {
            }
        });

        // 开线程定时结束loading
        EventHandler eventHandler = new EventHandler(EventRunner.getMainEventRunner());
        eventHandler.postTask(() -> {
            mErrImg.setVisibility(Component.VISIBLE);
            mLoadingLayout.setVisibility(Component.HIDE);
            mAnimatorProperty.stop();
            mAnimatorProperty.cancel();
            mAnimatorProperty = null;
        }, TOAST_SHOW_DURATION);
    }
}
